﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace LADA
{
    public class TransparentRichTextBox : RichTextBox
    {
        [DllImport("user32.dll")]
        private static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        private const int GWL_EXSTYLE = -20;
        private const int WS_EX_LAYERED = 0x80000;

        private Color _backColor = Color.FromArgb(128, 240, 240, 240); // 半透明白色

        public TransparentRichTextBox()
        {
            this.BorderStyle = BorderStyle.None;
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer |
                         ControlStyles.ResizeRedraw |
                         ControlStyles.AllPaintingInWmPaint, true);
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            SetWindowStyle();
        }

        private void SetWindowStyle()
        {
            if (this.IsHandleCreated)
            {
                int style = GetWindowLong(this.Handle, GWL_EXSTYLE);
                SetWindowLong(this.Handle, GWL_EXSTYLE, (IntPtr)(style | WS_EX_LAYERED));
            }
        }

        public new Color BackColor
        {
            get => _backColor;
            set
            {
                _backColor = value;
                this.Invalidate();
            }
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            // 绘制半透明背景
            using (var brush = new SolidBrush(_backColor))
            {
                e.Graphics.FillRectangle(brush, this.ClientRectangle);
            }

            // 调用基类方法以确保正常功能
            base.OnPaintBackground(e);
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_ERASEBKGND = 0x0014;

            if (m.Msg == WM_ERASEBKGND)
            {
                // 处理背景擦除消息，防止闪烁
                using (var g = Graphics.FromHdc(m.WParam))
                {
                    using (var brush = new SolidBrush(_backColor))
                    {
                        g.FillRectangle(brush, this.ClientRectangle);
                    }
                }
                m.Result = (IntPtr)1;
                return;
            }

            base.WndProc(ref m);
        }
    }
}